package com.aier.user.action;

import java.io.File;
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javassist.tools.reflect.Sample;

import javax.annotation.Resource;

import net.eicp.ghostboy.futil.MD5Util;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.aier.admin_new.entity.UserBean;
import com.aier.classes.entity.ClassParent;
import com.aier.classes.entity.ClassTeacher;
import com.aier.classes.service.IClassService;
import com.aier.classes.service.IClassUserService;
import com.aier.common.common.CommonSession;
import com.aier.common.common.Constant;
import com.aier.common.common.ImageUtil;
import com.aier.common.common.SystemConfigStatic;
import com.aier.user.common.TimerTest;
import com.aier.user.entity.User;
import com.aier.user.service.IUserService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Scope("prototype")
@Component("userAccountSettingsAction")
public class UserAccountSettingsAction extends UserBaseAction {

    /**
     * 账户设置
     */
    private static final long serialVersionUID = 1L;

    @Resource(name = "userService")
    private IUserService userService;
    @Resource(name = "classUserService")
    private IClassUserService classUserService;
    @Resource(name = "classService")
    private IClassService classService;

    private int s; // 成功:1 ,失败:0
    private String error_info; // 错误提示信息

    private User user; // 用户
    // private String account; //账号
    private String pwd; // 密码
    private String newpwd; // 新密码
    private String nickname; // 昵称
    private String realname; // 真实姓名
    // private String phone; //手机号(不是孩子账号时不能为空)
    private String email; // 邮箱
    private Integer city_id; // 所在地区id
    private String address; // 具体地址
    private String birthday; // 生日
    private String sex; // 性别
    private String desinfo; // 个人简介
    private String constellation; // 星座
    private String interest; // 爱好
    private String headimg; // 头像图片名
    private List<User> babyList; // 宝宝列表
    private Long baby_uid; // 宝宝uid
    private Long cid; // 班级id
    private String phone;
    private List<ClassParent> classParentList; // 班级家长身份列表
    private List<ClassTeacher> classTeacherList; // 班级教师身份列表


    private Long uid;

    private File file;
    
    private String appuserinfo;//app端的修改用户信息
    private String babysinfo;//
    // 图片原名
    private String photoName;
    private int x;
    private int y;
    private int w;
    private int h;

    @Override
    public String execute() {
        uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        user = userService.getUserByUid(uid);
        return SUCCESS;
    }

    /**
     * 修改用户信息
     * 
     * @return
     */
    public String updateUserInfo() {
        s = 1;
        Long uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        if (city_id != null && city_id == -1) {
            city_id = null;
        }
        if (userService.countUserByNickName(nickname, uid) > 0) {
            s = 0;
            error_info = "该昵称已经存在";
        } else {
            Date birthday_date = null;
            if (birthday != null && !"".equals(birthday)) {
                birthday_date = Date.valueOf(birthday);
            }
            user = new User(uid, nickname, realname, email, city_id, address,
                    birthday_date, sex, desinfo, constellation, interest);
            if (userService.updateUserInfo(user) == 0) {
                s = 0;
                error_info = "修改用户信息失败";
            }
        }
        return SUCCESS;
    }
    
    public String upUserinfo(){
    	int suss=userService.updateUserInfoNew(uid,email, phone, realname);
    	if ( suss== 0) {
            s = 0;
            error_info = "修改用户信息失败";
        }
    	  s = 1;
    	return SUCCESS;
    }
    
    /**
     * APP端更新用户信息
     * @return
     */
    public String updateUserInfoApp() {
    	 s = 1;
    	Gson gson=new Gson();
    	UserBean ua = gson.fromJson(appuserinfo, new TypeToken<UserBean>() {}.getType());
    	List<UserBean> is= gson.fromJson(babysinfo, new TypeToken<List<UserBean>>(){}.getType());
    	 if (userService.countUserByNickName(ua.getNickname(), uid) > 0) {
             s = 0;
             error_info = "该昵称已经存在";
         } else {
		        	 //改用户信息
		        	User users = new User();
		        	DateFormat df = new SimpleDateFormat("yyyy-MM-DD");
		        	users.setUid(Long.valueOf(ua.getUid()));
		        	try {
		    	    	if(ua.getBirthday()==null)
		    	    		ua.setBirthday("");
		    		    if(ua.getSex()==null)
		    		    	ua.setSex("");
		    		    if(ua.getDesinfo()==null)
		    		    	ua.setDesinfo("");
		    		    if(ua.getInterest()==null)
		    		    	ua.setInterest("");
		    		    if(ua.getAge()==null)
		    		    	ua.setAge("");
		    		    if(ua.getAddress()==null)
		    		    	ua.setAddress("");
		    		    
		    		   if(ua.getBirthday().equals("")==false){
						users.setBirthday(df.parse(ua.getBirthday()));
		    		   }
			        	users.setAccount(ua.getAccount());
			        	users.setNickname(ua.getNickname());
			        	users.setSex(ua.getSex());
			        	users.setDesinfo(ua.getDesinfo());
			        	users.setInterest(ua.getInterest());
			        	users.setAddress(ua.getAddress());
			        	userService.updateUserapp(users);
		        	} catch (ParseException e) {
						e.printStackTrace();
					}
		           
		        	//删除宝宝信息
		        	userService.deleteParentBabyApp(uid);
		        	//在更新
		             if(is.size()!=0){
			             for(UserBean u:is){
				    	    	if(u.getBirthday()==null)
				    	    		u.setBirthday("");
				    		    if(u.getSex()==null)
				    		    	u.setSex("");
				    		    if(u.getDesinfo()==null)
				    		    	u.setDesinfo("");
				    		    if(u.getInterest()==null)
				    		    	u.setInterest("");
				    		    if(u.getAge()==null)
				    		    	u.setAge("");

			            	users = new User();
			            	users.setUid(Long.valueOf(u.getUid()));
			              	try {
			              		if(u.getBirthday().equals("")==false){
			              			users.setBirthday(df.parse(u.getBirthday()));
			              		}
				              	users.setAccount(Math.random()*100000+u.getAccount());
				              	users.setNickname(u.getNickname());
				              	users.setSex(u.getSex());
				              	users.setDesinfo(u.getDesinfo());
				              	users.setInterest(u.getInterest());
				            	userService.updateBabyinfo(uid, users);
			              	} catch (ParseException e) {
								e.printStackTrace();
							}
			             }
             }
         }
    	 return SUCCESS;
    }
    

    /**
     * 修改用户头像(JQUERY版)
     * 
     * @return
     */
    public String updateUserHeadImg() {

        headimg = ImageUtil.uploadImage(file, upload_picturl_url, photoName, 0);

        s = 1;
        return SUCCESS;
    }

    /**
     * 修改用户头像(flash版)
     * 
     * @return
     */
    public String updateUserHImg() {
        
        headimg = ImageUtil.uploadImageAdjustable(file, upload_picturl_url, photoName, Constant.num_100, 
                Constant.num_100, Constant.num_200, Constant.num_200, true);
        Long uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        if (userService.updateUserHeadImg(uid, headimg) == 0) {
            s = 0;
            error_info = "修改用户头像失败";
        } else {
            s = 1;
        }
        return SUCCESS;
    }

    // 剪切用户头像
    public String cutImg() {

        s = ImageUtil.cutImg(SystemConfigStatic.upload_picturl_url, headimg, x,
                y, w, h);
        Long uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        if (userService.updateUserHeadImg(uid, headimg) == 0) {
            s = 0;
            error_info = "修改用户头像失败";
        } else {
            s = 1;
        }
        return SUCCESS;
    }
    // 读取用户头像
    public String serachAvatar() {
        User u = userService.getUserByUid((Long) session
                .get(CommonSession.SESSION_ACCOUNT_ID));
        if (null != u) {
            headimg = u.getHeadimg();
        }
        return SUCCESS;
    }
    

    /**
     * 修改密码
     * 
     * @return
     */
    public String updateNewPwd() {
        s = 1;
        Long uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        String account = userService.getUserByUid(uid).getAccount();
        if (userService.searchUserByCondition(account, MD5Util.getMD5(pwd)) != null) {
            if (userService.updateUserPwd(account, MD5Util.getMD5(newpwd)) == 0) {
                s = 0;
            }
        } else {
            s = 0;
            error_info = "原密码输入有误";
        }
        return SUCCESS;
    }

    // 显示我的班级列表(家长,教师)
    public String showMyclassList() {
        Long uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        classParentList = classUserService.searchClassParentListByUid(uid);
        classTeacherList = classUserService.searchClassTeacherListByUid(uid);
        return SUCCESS;
    }

    // 退出班级(家长身份)
    public String deleteParentClass() {
        Long uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        s = classUserService.deleteParentClass(uid, cid);
        return SUCCESS;
    }

    // 退出班级(教师身份)
    public String deleteTeacherClass() {
        Long uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        s = classUserService.deleteTeacherClass(uid, cid);
        return SUCCESS;
    }

    /**
     * 显示我的孩子列表
     * 
     * @return
     */
    public String showMyBabys() {
        Long uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        headimg = userService.getUserByUid(uid).getHeadimg();
        babyList = userService.searchUserBabyList(uid);
        if (babyList != null && babyList.size() > 0) {
            s = 1;
        } else {
            s = 0;
        }
        return SUCCESS;
    }

    /**
     * 取消和宝宝的关联关系
     * 
     * @return
     */
    public String delete_baby() {
        Long parent_uid = (Long) session.get(CommonSession.SESSION_ACCOUNT_ID);
        s = userService.deleteParentBaby(parent_uid, baby_uid);
        return SUCCESS;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public void setNewpwd(String newpwd) {
        this.newpwd = newpwd;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    // public void setPhone(String phone) {
    // this.phone = phone;
    // }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setCity_id(Integer city_id) {
        this.city_id = city_id;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setDesinfo(String desinfo) {
        this.desinfo = desinfo;
    }

    public void setConstellation(String constellation) {
        this.constellation = constellation;
    }

    public void setInterest(String interest) {
        this.interest = interest;
    }

    public void setHeadimg(String headimg) {
        this.headimg = headimg;
    }

    public void setBaby_uid(Long baby_uid) {
        this.baby_uid = baby_uid;
    }

    public void setClassUserService(IClassUserService classUserService) {
        this.classUserService = classUserService;
    }

    public void setClassService(IClassService classService) {
        this.classService = classService;
    }

    public void setCid(Long cid) {
        this.cid = cid;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setW(int w) {
        this.w = w;
    }

    public void setH(int h) {
        this.h = h;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public void setPhotoName(String photoName) {
        this.photoName = photoName;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }

    public String getHeadimg() {
        return headimg;
    }

    public int getS() {
        return s;
    }

    public User getUser() {
        return user;
    }
    

    public void setUser(User user) {
		this.user = user;
	}

	public String getError_info() {
        return error_info;
    }

    public List<User> getBabyList() {
        return babyList;
    }
    
    public void setBabyList(List<User> babyList) {
		this.babyList = babyList;
	}

	public List<ClassParent> getClassParentList() {
        return classParentList;
    }

    public List<ClassTeacher> getClassTeacherList() {
        return classTeacherList;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getW() {
        return w;
    }

    public int getH() {
        return h;
    }

    public Long getUid() {
        return uid;
    }

	public void setAppuserinfo(String appuserinfo) {
		this.appuserinfo = appuserinfo;
	}

	public void setBabysinfo(String babysinfo) {
		this.babysinfo = babysinfo;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}
}